<?php
// 应用公共文件


/**
 * 获取IP
 * @return string
 */
function getIp(): string
{
    if (!empty(request()->server('HTTP_X_FORWARDED_FOR'))) {
        $ip_address = request()->server('HTTP_X_FORWARDED_FOR');
    } elseif (!empty(request()->server('HTTP_CLIENT_IP'))) {
        $ip_address = request()->server('HTTP_CLIENT_IP');
    } else {
        $ip_address = request()->server('REMOTE_ADDR');
    }
    $ip_address = explode(',', $ip_address);
    return $ip_address[0] ?? '';
}

/**
 * 获取下级id
 * @param $list
 * @param int $pid
 * @param bool $isFirstTime
 * @return array
 */
function getAllLowerLevelId($list, int $pid = 0, bool $isFirstTime = true): array
{
    static $arr = [];
    if ($isFirstTime) {
        $arr = [];
    }
    foreach ($list as $val) {
        if ($val['pid'] == $pid) {
            $arr[] = $val['id'];
            getAllLowerLevelId($list, $val['id'], false);
        }
    }
    return $arr;
}


/**
 * 过滤敏感词
 * @param string $text 过滤内容
 * @param array $sensitiveWords 敏感词数组
 */
function filterSensitiveWords(string $text, array $sensitiveWords): array|string|null
{
    $pattern = '/(' . implode('|', $sensitiveWords) . ')/iu';
    return preg_replace_callback($pattern, function ($matches) {
        return str_repeat('*', strlen($matches[0]));
    }, $text);
}

/**
 * oss上传
 * @param $path
 * @param $ext
 * @return mixed
 */
function oss($path, $ext): mixed
{
    $upload = new \app\common\Upload();
    // 设置上传类型和文件大小
    $upload = $upload->defaultConfig();
    $fileContent = file_get_contents($path);
    return $upload->upload($fileContent, 'binary', $ext);
}

/**
 * 拼接oss文件地址
 * @param $path
 * @return string
 */
function ossStaticPath($path): string
{
    $config = config('app.oss');
    return $config['static_url'] . '/' . $config['static_path'] . $path;
}

/**
 * 验证身份证规则
 * @param string $id 身份证号
 * @return false|int
 */
function isIdCard(string $id): bool|int
{
    $pattern = "/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/";
    return preg_match($pattern, $id);
}

/**
 * word转PDF
 * @param $files
 */
function WordToPdf($files): void
{
    //线上
//    $win_exce = '/opt/libreoffice7.4/program/soffice --headless --convert-to pdf ' . $files . ' --outdir ' . dirname($files);
    //本地
//    $win_exce = '/usr/lib64/libreoffice/program/soffice --headless --convert-to pdf ' . $files . ' --outdir ' . dirname($files);
    //本地ubuntu系统
    $win_exce = 'libreoffice --headless --convert-to pdf ' . $files . ' --outdir ' . dirname($files);
    Swoole\Coroutine\System::exec($win_exce);
}

/**
 * 自定义时间段
 * @param array $date
 * @param string $type
 * @return array
 */
function custom_time(array $date = [], string $type = 'd'): array
{
    $data = [];
    $j = 1;
    if (count($date) > 1) {
        switch ($type) {
            case 'd':
                $day_num = (strtotime($date[1]) - strtotime($date[0])) / (3600 * 24);
                break;
            case 'm':
                $date1 = explode('-', $date[1]);
                $date2 = explode('-', $date[0]);
                $day_num = abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);
                break;
            case 'y':
                $day_num = $date[1] - $date[0];
                break;
            default:
                $day_num = (strtotime($date[1]) - strtotime($date[0])) / (3600 * 24);
        }
        //组合数据
        for ($i = $day_num; $i >= 0; $i--) {
            switch ($type) {
                case 'd':
                    $data[$j]['start_time'] = date('Y-m-d 00:00:00', strtotime($date[1]) - ($i * 24 * 3600));
                    $data[$j]['end_time'] = date('Y-m-d 23:59:59', strtotime($date[1]) - ($i * 24 * 3600));
                    $data[$j]['value'] = date('Y-m-d', strtotime($data[$j]['start_time']));
                    break;
                case 'm':
                    if ($i == 0) {
                        $m = date('Y-m-01', strtotime(date($date[1] . '-01') . '+1month'));
                    } else {
                        $m = date('Y-m-01', strtotime(date($date[1] . '-01') . '-' . ($i - 1) . 'month'));
                    }
                    $data[$j]['start_time'] = date('Y-m-01 00:00:00', strtotime($m . '-1 month'));
                    $data[$j]['end_time'] = date('Y-m-d 23:59:59', strtotime($m . ' -1 day'));
                    $data[$j]['value'] = date('Y-m', strtotime($data[$j]['start_time']));
                    break;
                case 'y':
                    if ($i == 0) {
                        $y = date('Y-01-01', strtotime(date($date[1] . '-01-01') . '+1year'));
                    } else {
                        $y = date('Y-01-01', strtotime(date($date[1] . '-01-01') . '-' . ($i - 1) . 'year'));
                    }
                    $data[$j]['start_time'] = date('Y-01-01 00:00:00', strtotime($y . '-1 year'));
                    $data[$j]['end_time'] = date('Y-m-d 23:59:59', strtotime($y . '-1 day'));
                    $data[$j]['value'] = date('Y', strtotime($data[$j]['start_time'])) . '年';
                    break;
            }
            $j++;
        }
    } else {
        //组合数据
        for ($i = 6; $i >= 0; $i--) {
            switch ($type) {
                case 'd':
                    $data[$j]['start_time'] = date('Y-m-d 00:00:00', strtotime('-' . $i . 'day'));
                    $data[$j]['end_time'] = date('Y-m-d 23:59:59', strtotime('-' . $i . 'day'));
                    $data[$j]['value'] = date('Y-m-d', strtotime($data[$j]['start_time']));
                    break;
                case 'm':
                    if ($i == 0) {
                        $m = date('Y-m-01', strtotime(date('Y-m-d') . '+1month'));
                    } else {
                        $m = date('Y-m-01', strtotime(date('Y-m-d') . '-' . ($i - 1) . 'month'));
                    }
                    $data[$j]['start_time'] = date('Y-m-01 00:00:00', strtotime('-' . $i . 'month'));
                    $data[$j]['end_time'] = date('Y-m-d 23:59:59', strtotime($m . ' -1 day'));
                    $data[$j]['value'] = date('Y-m', strtotime($data[$j]['start_time']));
                    break;
                case 'y':
                    if ($i == 0) {
                        $y = date('Y-01-01', strtotime(date('Y-m-d') . '+1year'));
                    } else {
                        $y = date('Y-01-01', strtotime(date('Y-m-d') . '-' . ($i - 1) . 'year'));
                    }
                    $data[$j]['start_time'] = date('Y-01-01 00:00:00', strtotime('-' . $i . 'year'));
                    $data[$j]['end_time'] = date('Y-m-d 23:59:59', strtotime($y . '-1 day'));
                    $data[$j]['value'] = date('Y', strtotime($data[$j]['start_time'])) . '年';
                    break;
            }
            $j++;
        }
    }
    return $data;

}


/**
 * 把数组按照树排列
 * @author ycxiao
 * */
function array_to_tree(array &$input, &$return, $thisPid = 0, $pidKey = 'pid'): void
{
    foreach ($input as $key => $value) {
        if ($value[$pidKey] == $thisPid) {
            if ($thisPid == 0) {
                $return[$key] = $value;
            } else {
                $return[$thisPid]['children'][] = $value;
            }
            unset($input[$key]);
            if (!empty($input)) {
                array_to_tree($input, $return, (int)$key);
            }
        }
    }
}


//三维数组转二维数组【降一维。】
function arrtre($arrs): array
{
    $stud = array();
    foreach ($arrs as $value) {
        foreach ($value as $v) {
            $stud[] = $v;
        }
    }
    return $stud;
}

/**
 * 去掉小数点后最后一位是0的 ，例如：12.40 输出 12.4
 * @param $number
 * @return string
 */
function removeTrailingZero($number): string
{
    // 将数字转换为字符串
    $numStr = (string)$number;

    // 检查是否存在小数点
    if (str_contains($numStr, '.')) {
        // 去掉小数部分最后的0
        $numStr = rtrim($numStr, '0'); // 去掉右侧的0
        // 如果小数部分变为空，去掉小数点
        $numStr = rtrim($numStr, '.');
    }
    return $numStr;
}

/**
 * 二维数组根据字符去重
 * @param $arr
 * @param $key //字段
 * @return array
 */
function arrayUniqueKey($arr, $key): array
{
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
        if (in_array($v[$key], $tmp_arr))   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
        {
            unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
        } else {
            $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
            // array_push($tmp_arr,$v[$key]);
        }
    }
    //ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
    return array_values($arr);
}

/**
 * 规则树
 * @param $data
 * @param $parent_id
 * @return array
 */
function rule_trees($data, $parent_id = 0): array
{
    $res = [];
    foreach ($data as $v) {
        if ($v['pid'] == $parent_id) {
            $v['children'] = rule_trees($data, $v['id']);
            $res[] = $v;
        }
    }
    return $res;
}

/**
 *  查询指定的节点的所有父级
 * @param $treeData //树形数据
 * @param $nodeId //节点id【要查询的节点id】
 * @return array
 */
function getParents($treeData, $nodeId): array
{
    // 初始化结果集合
    $parents = [];
    foreach ($treeData as $item) {
        if ($item['id'] == $nodeId) {
            $parents[] = $item;
            // 若还有上级节点，则继续递归查询
            if (isset($item['pid']) && $item['pid'] != $nodeId) {
                $result = getParents($treeData, $item['pid']);
                // 将上级节点也添加到结果集合中
                $parents = array_merge($parents, $result);
            }
            break;
        } elseif (!empty($item['children'])) {
            // 若当前节点有子节点，则递归查询子节点
            $result = getParents($item['children'], $nodeId);
            // 将子节点的父级节点都添加到结果集合中
            $parents = array_merge($parents, $result);
        }
    }
    return $parents;
}

/**
 * 校验参数是否存在一个二维数组中
 * @param string $value //参数值 [可能存在(字段类型)的问题，自行查看参数]
 * @param array $array //二维数组
 * @param string $field //二维数组内的数组中的字段 [必传]
 * @return bool  //true:表示存在这个数组中。false:表示不存在这个数组中
 */
function in_array_2d($value, $array, $field): bool
{
    foreach ($array as $item) {
        if ($value == $item[$field]) {
            return true;
        }
    }
    return false;
}


/**
 * 将一个多维数组中的所有子数组的元素提取出来，并返回一个一维数组
 * 例如：
 * $list = [[1, 2],[3, 4],[5]];
 * 调用 arrayDrop($list) 将返回：
 *  [1, 2, 3, 4, 5]
 * @param $list
 * @return mixed
 */
function arrayDrop($list): mixed
{
    return array_reduce($list, function ($carry, $item) {
        return array_merge($carry, array_values($item));
    }, []);
}

/**
 * 校验是否存在并且是否不为空
 * @return bool true:存在不为空
 * @author ycxiao
 * */
function check_array_key($key, $data): bool
{
    if (key_exists($key, $data)) {
        if (!empty($data[$key])) {
            return true;
        }
        if ($data[$key] === 0 || $data[$key] === '0') {
            return true;
        }
    }
    return false;
}

/**
 * 获取部门完整名称
 * @param array $list
 * @param int $id
 * @return string
 */
function getCompleteDepartmentName(array $list, int $id): string
{
    $name = '';
    $i = 0;
    while ($id) {
        if ($i > 10) break;//防止死循环
        foreach ($list as $item) {
            if ($item['id'] == $id) {
                $name = $item['name'] . $name;
                $id = $item['pid'];
                break;
            }
        }
        $i++;
    }
    return $name;
}

/**
 * 将数组分页
 * @param $array
 * @param $page
 * @param $pageSize
 * @return array
 */
function paginateArray($array, $page, $pageSize): array
{
    $totalItems = count($array);
    $totalPages = ceil($totalItems / $pageSize);
    $currentPage = max(min($page, $totalPages), 1);
    $offset = ($currentPage - 1) * $pageSize;
    return [
        'items' => array_slice($array, $offset, $pageSize),
        'meta' => [
            'total_items' => $totalItems,
            'total_pages' => $totalPages,
            'current_page' => $currentPage,
        ]
    ];
}

/**
 * 获取所有下级
 * @param $categories
 * @param int $parentId
 * @return array
 */
function getAllSubcategories($categories, int $parentId = 0): array
{
    $subcategories = array();
    foreach ($categories as $category) {
        if ($category['pid'] == $parentId) {
            $subcategories[] = $category;
            $subcategories = array_merge($subcategories, getAllSubcategories($categories, $category['id']));
        }
    }
    return $subcategories;
}

/**
 * 验证账号
 * @param $account
 * @return bool
 */
function validateAccount($account): bool
{
    return strlen($account) >= 6 && strlen($account) <= 18;
}

/**
 * 把数组按照数组内有的指定的key重新排列，限定二维数组
 * @author ycxiao
 * */
function set_array_key($array, $key = 'id', $onlyKey = ''): array
{
    $return = [];
    foreach ($array as $value) {
        $return[$value[$key]] = empty($onlyKey) ? $value : $value[$onlyKey];
    }
    return $return;
}

/**
 * 验证是否为中文
 * @param $string
 * @return false|int
 */
function isChinese($string): bool|int
{
    return preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $string);
}

/**
 * 解析算法【字符串匹配：这里是找到"/"之后得所有数值】
 * @param $string
 * @return float|int|null
 */
function matchNumberAfterSlash($string): float|int|null
{
    if (!empty($string)) {
        // 使用正则表达式捕获组提取数字
        preg_match('/\/\s*([0-9]+(?:\.[0-9]+)?)/u', $string, $number);
        return (float)$number[1]; // 转换为整数并返回
    }
    return null; // 如果没有匹配到，返回null
}

function matchNumberMultiplication($string)
{
    if (!empty($string)) {
        // 使用正则表达式捕获组提取数字
        preg_match('/\*\s*([0-9]+(?:\.[0-9]+)?)/u', $string, $number);
        return (float)$number[1]; // 转换为整数并返回
    }
    return null; // 如果没有匹配到，返回null
}

/**
 * 判断re
 * @param array $array
 * @return bool
 */
function is_re(array $array = []): bool
{
    foreach ($array as $item) {
        if (!$item) return false;
    }
    return true;
}

/**
 * 账号验证（策略规则）
 * @param $username
 * @return bool
 */
function validateUsername($username): bool
{
    $validLength = strlen($username) >= 8 && strlen($username) <= 18;
    return $validLength;
}

/**
 * 密码验证（策略规则）
 * @param $password
 * @return bool
 */
function validatePassword($password): bool
{
//    $lowercase = preg_match('`[a-z]`', $password);
//    $uppercase = preg_match('`[A-Z]`', $password);
//    $number = preg_match('`[0-9]`', $password);
//    $specialChar = preg_match('`[!@#$%^&*()\-_=+{};:,<.>]`', $password);
//    $validLength = strlen($password) >= 8 && strlen($password) <= 18;
//    return $lowercase && $uppercase && $number && $specialChar && $validLength;

    $validLength = strlen($password) >= 8 && strlen($password) <= 18;
    return $validLength;
}

/**
 * aes-256-cbc加密
 * @param string $str 需要加密的字符串
 * @return false|string
 */
function aesEncryption(string $str): bool|string
{
//    $iv = env('AES_IV');
    $secretKey = env('AES_SECRET_KEY'); // 密钥应该是16字节（AES-128）或者32字节（AES-256）
//    $text = openssl_encrypt($str, 'AES-256-CBC', $secretKey, 0,$iv);
    $text = openssl_encrypt($str, 'AES-128-ECB', $secretKey, OPENSSL_RAW_DATA);
    // 加密
    return base64_encode($text);
}

/**
 * aes-256-cbc解密
 * @param string $str 需要解密的字符串
 * @return false|string
 */
function aesDecrypt(string $str): bool|string
{
//    $iv = env('AES_IV');
    $secretKey = env('AES_SECRET_KEY'); // 密钥应该是16字节（AES-128）或者32字节（AES-256）
    $text = base64_decode($str);
    // 解密
//    return openssl_decrypt($text, 'AES-256-CBC', $secretKey, 0,$iv);
    return openssl_decrypt($text, 'AES-128-ECB', $secretKey, OPENSSL_RAW_DATA);
}

/**
 * 递归创建目录
 * @param string $dir
 * @return bool|void
 */
function folder_build(string $dir = '')
{
    if (!is_dir($dir)) {
        while (!is_dir(dirname($dir))) {
            if (!folder_build(dirname($dir))) {
                echo error($dir . '目录写入失败');
                exit();
            }
        }
        if (!is_writable($dir)) {
            return mkdir($dir, 0777, true);
        } else {
            echo error($dir . '目录不可写');
            exit();
        }
    }
}

/**
 * 多级树状图
 * @param array $array
 * @param int $parentId
 * @param string $pidField
 * @param string $idField
 * @return array
 */
function buildTree(array $array, int $parentId = 0, string $pidField = 'pid', string $idField = 'id'): array
{
    if (empty($array)) {
        return [];
    }
    $fotmatTree = array();
    foreach ($array as $item) {
        if ($item[$pidField] == $parentId) {
            $child = buildTree($array, $item[$idField], $pidField, $idField);
            if ($child) {
                $item['child'] = $child;
            }
            $fotmatTree[] = $item;
        }
    }
    return $fotmatTree;
}

/**
 * 通用化接口封装
 * @param $status //方法状态码 200：成功;0:失败
 * @param $message //返回消息;
 * @param $data //要返回的数据。
 * @param $httpCode //http 状态码
 */
function show($status, $message, $data, $httpCode): bool|string
{
    $data = [
        'code' => $status,
        'message' => $message,
        'data' => $data,
    ];
    return json_encode($data, $httpCode);
}


/**
 * 返回error
 * @author ycxiao
 * */
function error($message = 'error', $code = 0, $data = [], $httpCode = JSON_UNESCAPED_UNICODE): bool|string
{
    return show($code, $message, $data, $httpCode);
}


/**
 * 返回success
 * @author ycxiao
 * */
function success($data = [], $message = 'success', $code = 200, $httpCode = JSON_UNESCAPED_UNICODE): bool|string
{
    return show($code, $message, $data, $httpCode);
}


/**
 * 获取加密后的字符串
 * @author ycxiao
 * */
function encrypt_password($password, $entry = 'jkyl'): string
{
    return md5(md5($password) . $entry);
}

/**
 * 生成登录token令牌
 * @param $user
 * @param string $model token使用在那个模块
 * @return string
 * @return string
 */
function generateLoginToken($user, string $model = 'jkyl_'): string
{
    $token = time() . uniqid() . 'uid' . $user['id'];
    $token = md5($token);
    $token_key = 'is_' . $model . $user['id'];
    $is_token_key = cache($token_key);
    if ($is_token_key) {
        cache($is_token_key, null);
    }
    $time = 60 * 60 * 24;
    cache($token_key, $model . $token, $time);
    cache($model . $token, $user, $time);
    return $token;
}

/**
 * @param $name
 * @return string
 * 驼峰转换
 */
function filterMethod($name): string
{
    // GoodId 转换成 Good_Id , 左边是小写才添加_ , aGoodId 转换成a_Good_Id
    $name = preg_replace("/(?<=[a-z])([A-Z])/", "_$1", $name);
    return strtolower($name);
}

/**
 * 获取全局随机字符串
 * @param int $size
 * @param int $case 1 数字加小写字母，2 纯数字，3 数字加大写字母， 4 大写字母， 5小写字母， 其他包含全部
 * @return bool|string
 */
function qCode(int $size = 8, int $case = 1): bool|string
{
    $str = match ($case) {
        1 => '0123456789abcdefghijklmnopqrstuvwxyz',
        2 => '0123456789',
        3 => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        4 => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        5 => 'abcdefghijklmnopqrstuvwxyz',
        default => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    };
    $arr = str_split($str);
    $count = count($arr);
    if (!$count) return false;
    $ret = '';
    for ($i = 0; $i < $size; $i++) {
        $ret .= $arr[rand(0, $count - 1)];
    }
    return $ret;
}

/**
 * 获取当前访问地址
 * @param bool $noport
 * @return array|string|string[]
 */
function get_http_url(bool $noport = false): array|string
{
    if (php_sapi_name() == 'cli') {
        $url = 'https://jkyl2.fucity.cn/'; // 获取域名
    } else {
        if (is_https()) {
            $url = 'https://' . $_SERVER['HTTP_HOST'];
        } else {
            $url = 'http://' . $_SERVER['HTTP_HOST'] ?? 'default.local';
        }
        if ($noport) {
            $url = str_replace(':' . $_SERVER['SERVER_PORT'], '', $url);
        }
    }
    return $url;
}

/**
 * 判断当前是否为https
 * @return bool
 */
function is_https(): bool
{
    if ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on')) {
        return true;
    } elseif (isset($_SERVER['REQUEST_SCHEME']) && strtolower($_SERVER['REQUEST_SCHEME']) == 'https') {
        return true;
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
        return true;
    } elseif (isset($_SERVER['HTTP_X_CLIENT_SCHEME']) && strtolower($_SERVER['HTTP_X_CLIENT_SCHEME']) == 'https') {
        return true;
    } else {
        return false;
    }
}

/**
 * 请求第三方接口
 * @param $url
 * @param array $data
 * @param array $arr
 * @param string $ip
 * @return array|false|string
 */
function get_curl($url, array $data = [], array $arr = [], string $ip = '')
{
    /*
     * curl封装(Get方式)
     * $url		地址
     * $arr['header'] = 设置header头
     * $arr['out_time'] = 超时
     * $arr['is_header'] = 是否返回header头
     * $arr['is_location'] = 是否跟随header跳转
     * */
    if (@!$arr['header']) {
        $arr['header'] = array(
            'User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36',
        );
    }
    if (@!$arr['out_time']) {
        $arr['out_time'] = 20;
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($data) {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    } else {
//        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'OPTIONS');
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    }
    if ($ip) {
        //有ip就代理
        $Port = $url;
        $Port = explode(':', $Port);
        if (@$Port[1]) {
            $Port = $Port[1];
        } else {
            $Port = 80;
        }
        curl_setopt($ch, CURLOPT_PROXYPORT, $Port);
        curl_setopt($ch, CURLOPT_PROXY, $ip);
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);    //不检测证书
    curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']);    //发送header头
    curl_setopt($ch, CURLOPT_TIMEOUT, $arr['out_time']);    //超时
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, @$arr['is_location']);//是否跟随跳转
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//不输出内容
    if ($data) {
        if (@$arr['jsonData'])
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        else if (@$arr['jsonData2'])
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
        else if (@$arr['nData'])
            curl_setopt($ch, CURLOPT_POSTFIELDS, ($data));
        else
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    }
    curl_setopt($ch, CURLOPT_HEADER, true);        //返回header头
    $temp = curl_exec($ch);
    $hader_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    curl_close($ch);
    unset($ch);

    $header = substr($temp, 0, $hader_size);
    $content = substr($temp, $hader_size);

    $gzip_count = false;
    preg_match_all('/Content-Encoding[\s]*:[\s]*([\w\d]+)[\s|$]+/iU', $header, $temp);
    if (isset($temp[1][0]) && strtolower(@$temp[1][0]) == 'gzip') {
        //支持gzip解压
        $gzip_count = strlen($content);
        $content = gzdecode($content);
    }

    if (@$arr['is_header']) {
        //需要返回头+conent内容
        return array('header' => $header, 'gzip_count' => $gzip_count, 'content' => $content);
    }
    //仅返回content内容
    return $content;

}


